from aiCube import AICube
from gameServer import gameServer
from eventServer import eventServer
from vec2 import Vec2
from copy import copy

class NearestAttack(AICube):
    def __init__(self, player):
        AICube.__init__(self, player)
        
        self.defaultVar("retargetTime",1.0)
        self.retargetStartTime = None
        self.target = None
        
        eventServer.register("update",self.naUpdate)
        
    def naUpdate(self, cmd, args):
        if self.getVar("dead"):
            return
        
        time = args['time']
        
        if not self.retargetStartTime or time - self.retargetStartTime > self.getVar("retargetTime"):
            self.retargetStartTime = time
            
            self.target = None
            minDist = None
            myPlayer = self.getVar("player")
            myPos = self.getVar("pos")
            
            for i in range(4):
                if i != myPlayer:
                    playerName = "player%d" % i
                    player = gameServer.getObject(playerName)
                    if player and player.hasVar("pos") and not player.getVar("dead"):
                        dist = (player.getVar("pos") - myPos).length()
                        if not minDist or dist < minDist:
                            minDist = dist
                            self.target = playerName
                            
        if self.target:
            obj = gameServer.getObject(self.target)
            if obj and obj.hasVar("pos") and obj.hasVar("dead") and not obj.getVar("dead"):
                #print self.getVar("name"), "seek", self.target, obj.getVar("pos")
                pos = copy(obj.getVar("pos"))
                self.setVar("moveTo",Vec2(pos.x,pos.y))
